#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#
#
#

"""
Runs all scripts from the tests package.
"""

__author__ = 'DR0ID'
__last_change_by__ = '$Author$'
__revision__ = '$Revision$'
__date__ = '$Date$'
__license__ = 'see readme.txt'
__copyright__ = 'Dlacewell, DR0ID (c) 2008'
__url__ = 'http://code.google.com/p/bipy/'
__email__ = 'dr0iddr0id@googlemail.com, DLacewell@googlemail.com'

import os, os.path, sys, glob
import unittest, inspect
#BIPY_PATH = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
BIPY_PATH = os.path.split( os.path.abspath(__file__) )[0]
if BIPY_PATH not in sys.path:
    sys.path.insert(0, BIPY_PATH)

import bipy
import bipy.tests

modules = []

class TestImportsOfTestRunner(unittest.TestCase):

    def test_imports(self):
        module_file_names = glob.glob(os.path.join(bipy.tests.__path__[0], '*.py'))
        global modules
        for m in  module_file_names:
            try:
                name = os.path.split(m)[1]
                modules.append( (name, __import__('bipy.tests.'+name[:-3])))
            except Exception, e:
                msg = '\n(module %s could not be loaded!)'%(name[:-3])
                msg = str(e) + msg
                self.fail(msg)

def run():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestImportsOfTestRunner))
    res = unittest.TextTestRunner(verbosity=0).run(suite)
    if not res.wasSuccessful():
        res.printErrors()
        print_path_info()
    else:
        suite = unittest.TestSuite()
        try:
            global modules
            modules.extend(inspect.getmembers(bipy.tests, inspect.ismodule))
            classes = [inspect.getmembers(m[1], inspect.isclass) for m in modules]
            testclasses = [c for mc in classes for c in mc if issubclass(c[1], unittest.TestCase)]
            [suite.addTest(unittest.makeSuite(c[1])) for c in testclasses]
        except Exception, e:
            print e

        res = unittest.TextTestRunner(verbosity=2).run(suite)
        print_path_info()
        
def print_path_info():
    sys.stdout.write('\nTested bipy files from: \n\n%s \n\n'%(BIPY_PATH))
    sys.stdout.write('-'*70)
    sys.stdout.write('\n')


if __name__ == '__main__':
    run()